package com.h2cloud.service.jedis;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

/**
 * @Package: com.h2cloud.jedis
 * @ClassName: windowService
 * @Author: wulongkai
 * @CreateTime: 2023/8/4 15:14
 * @Description:
 */
@Service
@Slf4j
public class WindowService {

    private RedisClient redisClient = new RedisClient();
    int expireTime = 50; // 5秒超时时间

    public String openWindow(String lockKey, String requestId) throws Exception {
        System.out.println("openWindow requestId = " + requestId);
        boolean lock = redisClient.lock(lockKey, requestId, expireTime);
        if (!lock) {
            throw new Exception("获取锁失败");
        }

        System.out.println("openWindow 获取锁");
        try {
            new Thread(() -> {
                try {
                    doOpenWindow(lockKey, requestId);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }).start();
            Thread.sleep(10000);
            System.out.println("openWindow end");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            redisClient.unLock(lockKey, requestId);
        }

        return "开启中";
    }

    public String doOpenWindow(String lockKey, String requestId) throws Exception {
        boolean lock = redisClient.lock(lockKey, requestId, expireTime);
        if (!lock) {
            throw new Exception("获取锁失败");
        }

        System.out.println("doOpenWindow 获取锁");
        try {
            System.out.println("doOpenWindow 执行相关代码");
            Thread.sleep(15000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            redisClient.unLock(lockKey, requestId);
        }
        System.out.println("doOpenWindow end");
        return "开启中";
    }

}
